from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor
from datetime import datetime, timedelta
# 定义定时任务
from apscheduler.schedulers.blocking import BlockingScheduler

from goods.models import SKU
from orders.models import OrderGoods


def my_job(order_id, sku_id, stock, sales):
    order_goods = OrderGoods.objects.filter( order_id=order_id, sku_id=sku_id)
    order_goods.delete()
    try:
        sku = SKU.objects.get(id=sku_id)
        sku.stock += stock
        sku.sales -= sales
        sku.save()
    except Exception as e:
        print(e)
        sku = None

    print('my_job定时执行了。。。')


def my_job1(p1, p2):
    print('my_job1定时执行了。。。')
    print(p1)
    print(p2)


if __name__ == '__main__':
    executors = {
        'default': ThreadPoolExecutor(20)
    }
    now = datetime.now()
    # delay = now + timedelta(minutes=30)
    # delay = now + timedelta(minutes=1)
    delay = now + timedelta(seconds=10)
    # scheduler = BackgroundScheduler(executors=executors)

    scheduler = BlockingScheduler(executors=executors)
    # 向调度器中添加定时任务
    job = scheduler.add_job(my_job1, 'date', run_date=delay, args=[100, 'python'], id='my_job_id')
    print('job:', job)
    # 启动定时任务调度器工作
    scheduler.start()
    # scheduler.remove_job('my_job_id')  # 删除任务, 阻塞的，执行不了
    # job.remove()